// 全局变量
let currentUserId = null;

// 加载用户列表
async function loadUserList() {
    try {
        const response = await fetch('/api/admin/get_all_users');
        const data = await response.json();

        const userItems = document.getElementById('user-items');

        if (data.success && data.users && data.users.length > 0) {
            // 过滤只显示user_type为user的用户
            const filteredUsers = data.users.filter(user => user.user_type === 'user');

            userItems.innerHTML = '';
            filteredUsers.forEach(user => {
                const userItem = document.createElement('div');
                userItem.className = 'user-item';
                userItem.dataset.userId = user.user_id;
                userItem.innerHTML = `
                    <div class="user-avatar">
                        <i class="fas fa-user"></i>
                    </div>
                    <div class="user-info">
                        <div class="user-name">${user.username}</div>
                        <div class="user-id">ID: ${user.user_id}</div>
                    </div>
                `;

                // 绑定点击事件
                userItem.addEventListener('click', () => {
                    selectUser(user.user_id, user.username);
                });

                userItems.appendChild(userItem);
            });
        } else {
            userItems.innerHTML = '<div class="no-users">暂无用户数据</div>';
        }
    } catch (error) {
        console.error('加载用户列表失败:', error);
        document.getElementById('user-items').innerHTML = `
            <div class="error-message">
                <i class="fas fa-exclamation-triangle"></i>
                <span>加载用户失败，请刷新重试</span>
            </div>
        `;
    }
}

// 选择用户
async function selectUser(userId, userName) {
    // 更新当前选中的用户
    currentUserId = userId;

    // 更新UI
    document.getElementById('current-user').textContent = userName;
    document.getElementById('current-user-id').value = userId;

    // 高亮选中的用户
    document.querySelectorAll('.user-item').forEach(item => {
        item.classList.remove('active');
    });
    document.querySelector(`.user-item[data-user-id="${userId}"]`).classList.add('active');

    // 加载聊天记录
    await loadUserChatHistory(userId);
}

// 加载用户聊天历史
async function loadUserChatHistory(userId) {
    try {
        const response = await fetch(`/api/admin/get_user_chat_history?user_id=${userId}`);
        const data = await response.json();

        const chatMessages = document.getElementById('admin-chat-messages');
        chatMessages.innerHTML = '';

        if (data.success && data.history && data.history.length > 0) {
            // 按时间排序
            const sortedHistory = [...data.history].sort((a, b) =>
                new Date(a.created_at) - new Date(b.created_at)
            );

            // 渲染聊天记录
            sortedHistory.forEach(item => {
                addChatMessage(item.message, item.sender_type, item.created_at);
            });

            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        } else {
            chatMessages.innerHTML = `
                <div class="no-messages">
                    <i class="fas fa-comment-slash"></i>
                    <span>暂无聊天记录</span>
                </div>
            `;
        }
    } catch (error) {
        console.error('加载聊天历史失败:', error);
        document.getElementById('admin-chat-messages').innerHTML = `
            <div class="error-message">
                <i class="fas fa-exclamation-triangle"></i>
                <span>加载聊天记录失败</span>
            </div>
        `;
    }
}
// 添加加载和处理人工请求的函数
async function loadPendingRequests() {
    try {
        const response = await fetch('/api/admin/get_pending_chat_requests');
        const data = await response.json();

        const pendingRequests = document.getElementById('pending-requests');

        if (data.success && data.requests.length > 0) {
            pendingRequests.innerHTML = `<i class="fas fa-bell"></i> 有 ${data.requests.length} 个未处理的人工请求`;

            // 显示请求详情
            const requestList = document.getElementById('request-list');
            requestList.innerHTML = '';

            data.requests.forEach(request => {
                const requestDiv = document.createElement('div');
                requestDiv.className = 'pending-request-item';
                requestDiv.innerHTML = `
                    <div>用户ID: ${request.user_id}</div>
                    <div>请求时间: ${new Date(request.created_at).toLocaleString()}</div>
                    <div class="request-actions">
                        <button class="accept-btn" data-request-id="${request.request_id}" data-user-id="${request.user_id}">同意</button>
                        <button class="reject-btn" data-request-id="${request.request_id}">拒绝</button>
                    </div>
                `;
                requestList.appendChild(requestDiv);
            });

            // 绑定同意/拒绝按钮事件
            bindRequestActions();
        } else {
            pendingRequests.innerHTML = '';
        }
    } catch (error) {
        console.error('加载待处理请求失败:', error);
    }
}

// 绑定请求处理按钮事件
function bindRequestActions() {
    // 同意按钮
    document.querySelectorAll('.accept-btn').forEach(btn => {
        btn.addEventListener('click', async function() {
            const requestId = this.getAttribute('data-request-id');
            const userId = this.getAttribute('data-user-id');

            try {
                const response = await fetch(`/api/admin/accept_chat_request/${requestId}`, {
                    method: 'POST'
                });
                const data = await response.json();

                if (data.success) {
                    // 加载该用户的聊天记录
                    const userItem = document.querySelector(`.user-item[data-user-id="${userId}"]`);
                    if (userItem) userItem.click();

                    // 刷新请求列表
                    loadPendingRequests();
                }
            } catch (error) {
                console.error('处理请求失败:', error);
            }
        });
    });

    // 拒绝按钮
    document.querySelectorAll('.reject-btn').forEach(btn => {
        btn.addEventListener('click', async function() {
            const requestId = this.getAttribute('data-request-id');

            try {
                await fetch(`/api/admin/reject_chat_request/${requestId}`, {
                    method: 'POST'
                });
                // 刷新请求列表
                loadPendingRequests();
            } catch (error) {
                console.error('处理请求失败:', error);
            }
        });
    });
}

// 添加聊天消息到界面
function addChatMessage(message, senderType, timestamp) {
    const chatMessages = document.getElementById('admin-chat-messages');

    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${senderType}-message`;

    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';
    contentDiv.textContent = message;

    const timeDiv = document.createElement('div');
    timeDiv.className = 'message-time';

    // 格式化时间
    const date = new Date(timestamp);
    const timeString = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;

    // 设置发送者
    if (senderType === 'user') {
        timeDiv.textContent = `用户 ${timeString}`;
    } else if (senderType === 'bot') {
        timeDiv.textContent = `客服机器人 ${timeString}`;
    } else if (senderType === 'admin') {
        timeDiv.textContent = `我（管理员） ${timeString}`;
    }

    messageDiv.appendChild(contentDiv);
    messageDiv.appendChild(timeDiv);
    chatMessages.appendChild(messageDiv);
}

// 发送消息
d// 修改发送消息部分，确保sender_type正确
document.getElementById('admin-chat-form').addEventListener('submit', async function(e) {
    e.preventDefault();

    if (!currentUserId) {
        alert('请先选择用户');
        return;
    }

    const messageInput = document.getElementById('admin-message-input');
    const message = messageInput.value.trim();

    if (!message) return;

    try {
        // 发送消息到服务器
        const response = await fetch('/api/admin/send_message', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                user_id: currentUserId,
                message: message,
                sender_type: 'admin'  // 明确指定发送者类型
            })
        });

        const data = await response.json();

        if (data.success) {
            // 添加到聊天界面
            addChatMessage(message, 'admin', new Date().toISOString());

            // 清空输入框
            messageInput.value = '';

            // 滚动到底部
            const chatMessages = document.getElementById('admin-chat-messages');
            chatMessages.scrollTop = chatMessages.scrollHeight;
        } else {
            alert('发送消息失败: ' + (data.message || '未知错误'));
        }
    } catch (error) {
        console.error('发送消息失败:', error);
        alert('发送消息失败');
    }
});
// 添加加载售后订单的函数
async function loadAfterSalesOrders() {
    try {
        const response = await fetch('/api/admin/get_after_sales');
        const data = await response.json();

        const afterSalesList = document.getElementById('after-sales-list');

        if (data.success && data.orders.length > 0) {
            afterSalesList.innerHTML = '';
            data.orders.forEach(order => {
                const orderDiv = document.createElement('div');
                orderDiv.className = 'after-sales-order';
                orderDiv.innerHTML = `
                    <div>订单ID: ${order.order_id}</div>
                    <div>用户ID: ${order.user_id}</div>
                    <div>申请原因: ${order.reason}</div>
                    <div>申请时间: ${new Date(order.created_at).toLocaleString()}</div>
                    <div class="after-sales-actions">
                        <button class="approve-after-sales" data-id="${order.id}">同意</button>
                        <button class="reject-after-sales" data-id="${order.id}">拒绝</button>
                    </div>
                `;
                afterSalesList.appendChild(orderDiv);
            });

            // 绑定处理按钮事件
            bindAfterSalesActions();
        } else {
            afterSalesList.innerHTML = '<div>暂无售后申请</div>';
        }
    } catch (error) {
        console.error('加载售后订单失败:', error);
    }
}

// 绑定售后处理按钮事件
function bindAfterSalesActions() {
    // 同意按钮
    document.querySelectorAll('.approve-after-sales').forEach(btn => {
        btn.addEventListener('click', async function() {
            const id = this.getAttribute('data-id');
            await updateAfterSalesStatus(id, 'approved');
        });
    });

    // 拒绝按钮
    document.querySelectorAll('.reject-after-sales').forEach(btn => {
        btn.addEventListener('click', async function() {
            const id = this.getAttribute('data-id');
            await updateAfterSalesStatus(id, 'rejected');
        });
    });
}

// 更新售后状态
async function updateAfterSalesStatus(id, status) {
    try {
        const response = await fetch(`/api/admin/update_after_sales/${id}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ status: status })
        });

        const data = await response.json();
        if (data.success) {
            loadAfterSalesOrders(); // 刷新列表
        }
    } catch (error) {
        console.error('更新售后状态失败:', error);
    }
}
// 加载所有产品知识
async function loadAllProductKnowledge() {
    try {
        // 调用API获取真实数据
        const response = await fetch('/api/admin/product-knowledge');
        const data = await response.json();

        const tableBody = document.getElementById('knowledge-table-body');
        tableBody.innerHTML = '';

        if (data.success && data.knowledge && data.knowledge.length > 0) {
            data.knowledge.forEach(knowledge => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${knowledge.product_id}</td>
                    <td>${knowledge.name}</td>
                    <td>${knowledge.ingredients.substring(0, 20)}${knowledge.ingredients.length > 20 ? '...' : ''}</td>
                    <td>${knowledge.skin_type}</td>
                    <td class="table-actions">
                        <button class="action-btn edit-btn edit-knowledge" data-product-id="${knowledge.product_id}">编辑</button>
                        <button class="action-btn delete-btn delete-knowledge" data-product-id="${knowledge.product_id}">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });

            // 绑定编辑和删除按钮事件
            bindKnowledgeActions();
        } else {
            tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">暂无产品知识记录</td></tr>';
        }
    } catch (error) {
        console.error('加载产品知识错误:', error);
        document.getElementById('knowledge-table-body').innerHTML = `
            <tr>
                <td colspan="5" style="text-align: center; color: #e74c3c;">
                    加载产品知识失败: ${error.message}
                </td>
            </tr>
        `;
    }
}

// 绑定知识编辑和删除事件
function bindKnowledgeActions() {
    // 编辑按钮事件
    document.querySelectorAll('.edit-knowledge').forEach(button => {
        button.addEventListener('click', async function() {
            const productId = this.getAttribute('data-product-id');

            try {
                // 获取产品知识详情
                const response = await fetch(`/api/admin/product-knowledge?product_id=${productId}`);
                const data = await response.json();

                if (data.success && data.knowledge) {
                    const knowledge = data.knowledge;
                    document.getElementById('knowledge-modal-title').textContent = '编辑产品知识';
                    document.getElementById('knowledge-product-id').value = knowledge.product_id;
                    document.getElementById('knowledge-product-id-input').value = knowledge.product_id;
                    document.getElementById('knowledge-ingredients').value = knowledge.ingredients;
                    document.getElementById('knowledge-usage').value = knowledge.usage_instructions;
                    document.getElementById('knowledge-effect').value = knowledge.effect;
                    document.getElementById('knowledge-skin-type').value = knowledge.skin_type;
                    document.getElementById('knowledge-modal').style.display = 'flex';
                }
            } catch (error) {
                console.error('获取产品知识失败:', error);
                alert('加载产品知识失败');
            }
        });
    });

    // 删除按钮事件
    document.querySelectorAll('.delete-knowledge').forEach(button => {
        button.addEventListener('click', async function() {
            const productId = this.getAttribute('data-product-id');
            if (confirm('确定要删除这个产品知识吗？')) {
                try {
                    const response = await fetch(`/api/admin/product-knowledge?product_id=${productId}`, {
                        method: 'DELETE'
                    });
                    const data = await response.json();

                    if (data.success) {
                        alert('删除成功');
                        loadAllProductKnowledge();
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                } catch (error) {
                    console.error('删除产品知识错误:', error);
                    alert('删除失败');
                }
            }
        });
    });
}
document.getElementById('knowledge-form').addEventListener('submit', async function(e) {
    e.preventDefault();

    // 获取表单数据
    const knowledgeData = {
        product_id: document.getElementById('knowledge-product-id').value || document.getElementById('knowledge-product-id-input').value,
        ingredients: document.getElementById('knowledge-ingredients').value,
        usage_instructions: document.getElementById('knowledge-usage').value,
        effect: document.getElementById('knowledge-effect').value,
        skin_type: document.getElementById('knowledge-skin-type').value
    };

    try {
        let success = false;
        const productId = knowledgeData.product_id;

        if (productId) {
            // 更新产品知识
            const response = await fetch('/api/admin/product-knowledge', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(knowledgeData)
            });
            const data = await response.json();
            success = data.success;
        } else {
            // 添加新产品知识
            const response = await fetch('/api/admin/product-knowledge', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(knowledgeData)
            });
            const data = await response.json();
            success = data.success;
        }

        if (success) {
            document.getElementById('knowledge-modal').style.display = 'none';
            loadAllProductKnowledge(); // 重新加载产品知识列表
        } else {
            alert('保存产品知识失败');
        }
    } catch (error) {
        console.error('保存产品知识错误:', error);
        alert('保存产品知识失败');
    }
});


// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 检查登录状态
    checkAuthStatus();

    // 加载用户列表
    loadUserList();
    loadPendingRequests();
    
    // 加载产品数据
    loadProducts();
    
    // 绑定菜单点击事件
    document.querySelectorAll('.admin-menu a[data-view]').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有活动状态
            document.querySelectorAll('.admin-menu a').forEach(item => {
                item.classList.remove('active');
            });
            
            // 添加当前活动状态
            this.classList.add('active');
            
            // 显示对应视图
            const viewName = this.getAttribute('data-view');
            showView(viewName);
        });
    });
    
    // 产品表单提交事件
    document.getElementById('productForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveProduct();
    });
});



// 检查登录状态
async function checkAuthStatus() {
    try {
        const response = await fetch('/api/check-auth', {
            credentials: 'include'
        });
        
        const data = await response.json();
        
        if (!data.authenticated || data.user_type !== 'admin') {
            window.location.href = '/login';
        }
    } catch (error) {
        console.error('检查登录状态失败:', error);
        window.location.href = '/login';
    }
}

// 显示对应视图
function showView(viewName) {
    // 隐藏所有视图
    document.querySelectorAll('.admin-view').forEach(view => {
        view.style.display = 'none';
    });
    
    // 显示选中视图
    const view = document.getElementById(`${viewName}-view`);
    if (view) {
        view.style.display = 'block';
    } else {
        console.log(`视图 ${viewName} 不存在`);
    }
}

// 加载产品数据
async function loadProducts() {
    try {
        const response = await fetch('/api/admin/products');
        const data = await response.json();

        const tableBody = document.getElementById('products-table-body');

        if (data.success) {
            if (data.products && data.products.length > 0) {
                tableBody.innerHTML = '';

                data.products.forEach(product => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${product.product_id}</td>
                        <td>${product.name}</td>
                        <td>¥${product.price}</td>
                        <td>${product.stock}</td>
                        <td>${product.category}</td>
                        <td>${product.series}</td>
                        <td>
                            <button class="btn btn-small btn-primary edit-product" 
                                    data-product-id="${product.product_id}">编辑</button>
                            <button class="btn btn-small btn-danger delete-product" 
                                    data-product-id="${product.product_id}">删除</button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });

                // 绑定编辑按钮事件
                document.querySelectorAll('.edit-product').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const productId = this.getAttribute('data-product-id');
                        editProduct(productId);
                    });
                });

                // 绑定删除按钮事件
                document.querySelectorAll('.delete-product').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const productId = this.getAttribute('data-product-id');
                        deleteProduct(productId);
                    });
                });
            } else {
                tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无产品记录</td></tr>';
            }
        } else {
            tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #e74c3c;">加载产品失败</td></tr>';
        }
    } catch (error) {
        console.error('加载产品失败:', error);
        document.getElementById('products-table-body').innerHTML = '<tr><td colspan="7" style="text-align: center; color: #e74c3c;">加载产品失败</td></tr>';
    }
}

// 打开添加产品模态框
document.getElementById('add-product-btn').addEventListener('click', function() {
    document.getElementById('product-modal-title').textContent = '添加产品';
    document.getElementById('product-form').reset();
    document.getElementById('product-id').value = '';
    document.getElementById('product-modal').style.display = 'flex';
});

// 关闭产品模态框
document.getElementById('cancel-product').addEventListener('click', function() {
    document.getElementById('product-modal').style.display = 'none';
});

// 编辑产品
async function editProduct(productId) {
    try {
        const response = await fetch(`/api/admin/products/${productId}`);
        const data = await response.json();

        if (data.success && data.product) {
            const product = data.product;
            document.getElementById('product-modal-title').textContent = '编辑产品';
            document.getElementById('product-id').value = product.product_id;
            document.getElementById('product-name').value = product.name;
            document.getElementById('product-price').value = product.price;
            document.getElementById('product-stock').value = product.stock;
            document.getElementById('product-category').value = product.category;
            document.getElementById('product-series').value = product.series;
            document.getElementById('product-modal').style.display = 'flex';
        } else {
            alert('获取产品详情失败');
        }
    } catch (error) {
        console.error('编辑产品失败:', error);
        alert('获取产品详情失败');
    }
}

// 删除产品
async function deleteProduct(productId) {
    if (!confirm('确定要删除这个产品吗？此操作不可撤销！')) {
        return;
    }

    try {
        const response = await fetch(`/api/admin/products/${productId}`, {
            method: 'DELETE'
        });

        const data = await response.json();

        if (data.success) {
            alert('产品删除成功');
            loadProducts(); // 重新加载产品列表
        } else {
            alert('删除产品失败');
        }
    } catch (error) {
        console.error('删除产品失败:', error);
        alert('删除产品失败');
    }
}

// 保存产品（添加或更新）
document.getElementById('product-form').addEventListener('submit', async function(e) {
    e.preventDefault();

    const productId = document.getElementById('product-id').value;
    const productData = {
        name: document.getElementById('product-name').value,
        price: parseFloat(document.getElementById('product-price').value),
        stock: parseInt(document.getElementById('product-stock').value),
        category: document.getElementById('product-category').value,
        series: document.getElementById('product-series').value
    };

    try {
        let response;
        if (productId) {
            // 更新产品
            response = await fetch(`/api/admin/products/${productId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(productData)
            });
        } else {
            // 添加新产品
            response = await fetch('/api/admin/products', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(productData)
            });
        }

        const data = await response.json();

        if (data.success) {
            alert('产品保存成功');
            document.getElementById('product-modal').style.display = 'none';
            loadProducts(); // 重新加载产品列表
        } else {
            alert('保存产品失败');
        }
    } catch (error) {
        console.error('保存产品失败:', error);
        alert('保存产品失败');
    }
});

// 全局变量
let currentSession = null;

// 在DOMContentLoaded事件中添加：
document.getElementById('adminSendButton').addEventListener('click', sendAdminMessage);

// 加载转接请求
async function loadTransferRequests() {
    try {
        const response = await fetch('/api/transfer-requests');
        const requests = await response.json();

        const tableBody = document.getElementById('transferRequests');
        tableBody.innerHTML = '';

        requests.forEach(request => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${request.user_id}</td>
                <td>${request.session_id}</td>
                <td>${new Date(request.created_at).toLocaleString()}</td>
                <td>
                    <button class="btn btn-small btn-primary" 
                            onclick="acceptTransfer('${request.session_id}', '${request.user_id}')">
                        接入
                    </button>
                </td>
            `;
            tableBody.appendChild(row);
        });
    } catch (error) {
        console.error('加载转接请求失败:', error);
    }
}

// 接受转接
async function acceptTransfer(sessionId, userId) {
    try {
        // 获取聊天历史
        const response = await fetch(`/api/chat-history?session_id=${sessionId}`);
        const history = await response.json();

        // 显示聊天记录
        const chatContainer = document.getElementById('adminChatMessages');
        chatContainer.innerHTML = '';

        history.forEach(item => {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${item.is_human ? 'user' : 'bot'}-message`;
            messageDiv.textContent = item.is_human ? item.question : item.answer;
            chatContainer.appendChild(messageDiv);
        });

        // 保存当前会话
        currentSession = {
            sessionId,
            userId
        };

        // 滚动到底部
        chatContainer.scrollTop = chatContainer.scrollHeight;

        alert('已接入用户会话');
    } catch (error) {
        console.error('接入失败:', error);
        alert('接入失败');
    }
}

// 管理员发送消息
async function sendAdminMessage() {
    if (!currentSession) {
        alert('请先接入一个会话');
        return;
    }

    const message = document.getElementById('adminMessageInput').value.trim();
    if (!message) return;

    try {
        const response = await fetch('/api/admin-chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                session_id: currentSession.sessionId,
                user_id: currentSession.userId,
                message: message
            })
        });

        const data = await response.json();
        if (data.success) {
            // 添加到聊天界面
            const chatContainer = document.getElementById('adminChatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message admin-message';
            messageDiv.textContent = message;
            chatContainer.appendChild(messageDiv);

            // 清空输入框
            document.getElementById('adminMessageInput').value = '';

            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
    } catch (error) {
        console.error('发送消息失败:', error);
    }
}

// 加载售后服务
async function loadAfterSales() {
    try {
        const response = await fetch('/api/after-sales-requests');
        const requests = await response.json();

        const tableBody = document.getElementById('afterSalesTableBody');
        tableBody.innerHTML = '';

        requests.forEach(request => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${request.request_id}</td>
                <td>${request.order_id}</td>
                <td>${request.user_id}</td>
                <td>${request.service_type}</td>
                <td>${request.reason}</td>
                <td>${request.photo_url ? `<img src="${request.photo_url}" width="50">` : '无'}</td>
                <td>${new Date(request.created_at).toLocaleString()}</td>
                <td>${request.status}</td>
                <td>
                    <button class="btn btn-small btn-primary" 
                            onclick="reviewAfterSales('${request.request_id}', 'approve')">
                        通过
                    </button>
                    <button class="btn btn-small btn-danger" 
                            onclick="reviewAfterSales('${request.request_id}', 'reject')">
                        拒绝
                    </button>
                    <button class="btn btn-small" 
                            onclick="showAfterSalesDetails('${request.request_id}')">
                        详情
                    </button>
                </td>
            `;
            tableBody.appendChild(row);
        });
    } catch (error) {
        console.error('加载售后申请失败:', error);
    }
}

// 审核售后服务
async function reviewAfterSales(requestId, action) {
    if (!confirm(`确定要${action === 'approve' ? '通过' : '拒绝'}该申请吗？`)) {
        return;
    }

    try {
        const response = await fetch(`/api/after-sales/review/${requestId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: action
            })
        });

        const data = await response.json();
        if (data.success) {
            alert('操作成功');
            loadAfterSales();
        } else {
            alert('操作失败: ' + data.message);
        }
    } catch (error) {
        console.error('审核失败:', error);
        alert('审核失败');
    }
}

// 在showView函数中添加：
function showView(viewName) {
    // 隐藏所有视图
    document.querySelectorAll('.admin-view').forEach(view => {
        view.style.display = 'none';
    });

    // 显示选中视图
    const view = document.getElementById(`${viewName}-view`);
    if (view) {
        view.style.display = 'block';

        // 根据视图加载数据
        if (viewName === 'humanService') {
            loadTransferRequests();
        } else if (viewName === 'after-sales') {
            loadAfterSales();
        }
    } else {
        console.log(`视图 ${viewName} 不存在`);
    }
}